//
//  BusinessXVC.m
//  JinChengYun
//
//  Created by 金橙云 on 2017/3/24.
//  Copyright © 2017年 金橙云. All rights reserved.
//

#import "BusinessXVC.h"

#import "TodoHttpManager.h"


#import "RKTagsMenuView.h"//表头
#import "CustomCollectionViewCell.h"
#import "BusHouseXVC.h"
#import "Masonry.h"

#import "BusRenXViewController.h"//红色的
#import "MJRefresh.h"
@interface BusinessXVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

{
    NSArray *_unitArr;
    NSDictionary *_nameDic;
    NSMutableArray *_busXArr;
    NSString *_louStr;
    
    NSMutableDictionary *_firstDic;
    NSString *IDA;
    NSMutableDictionary *cellIdDic;//存放cell唯一标识符
    NSString *identifier;
    NSString *_colorStr;//颜色
    
    
    
    
    NSString *_newZong;
    NSString *_newYi;
    NSString *_newWei;
    NSString *bussSeleUnit;
}
@property (nonatomic, strong) NSMutableArray *oneArr;
@property (nonatomic,strong) NSMutableArray *qiArr;
@property(nonatomic,strong)UICollectionView *collectView;
@property (nonatomic,strong) NSMutableArray *qiIDArr;
@end

@implementation BusinessXVC


-(void)viewWillAppear:(BOOL)animated
{
   
    //表头通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTDZhuSBiaoTou:) name:TDZhuSBiaoTou object:nil];
    
    //房源(配套/商业)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTDZhuSHouse:) name:TDZhuSHouse object:nil];
    if (_unitArr.count == 0)
    {
        //TODO:表头
        [_manager userZhuShouHouseBiaoWithType:@"1" withQiShu:_IDStr];
        
        
    }

}

//表头通知方法
-(void)didTDZhuSBiaoTou:(NSNotification *)notifi
{
    if (notifi.object != 0)
    {
        int status = [[notifi.object objectForKey:@"status"] intValue];
        if (status == 1)
        {
            _unitArr = [notifi.object objectForKey:@"data"];
            
            _firstDic = [_unitArr objectAtIndex:0];
            _louStr = [_firstDic objectForKey:@"name"];
             bussSeleUnit = [_firstDic objectForKey:@"id"];

            for (int i = 0; i < _unitArr.count; i++) {
                
                NSDictionary *dict = [_unitArr objectAtIndex:i];
                [_qiArr addObject:dict[@"name"]];
                [_qiIDArr addObject:dict[@"id"]];
                
            }
          
           
            [self setupMenuQiArr:_qiArr];
           // [super viewDidLoad];
             [_collectView reloadData];
          
        }
        else
        {
            [_manager MakeMyselfAlert:@"获取失败" andIsNeedTitle:NO andShowTime:2.0];
        }
    }

    
}

//房源(配套/商业)
-(void)didTDZhuSHouse:(NSNotification *)noti
{
    if (noti.object != 0)
    {
        NSLog(@"--------%@---",noti.object);
        _newZong = [noti.object objectForKey:@"all_rooms"];
        _newYi = [noti.object objectForKey:@"sale_rooms"];
        _newWei = [noti.object objectForKey:@"rest_rooms"];
        int status = [[noti.object objectForKey:@"status"] intValue];
        if (status == 1)
        {
           // _oneArr = (NSMutableArray *)[noti.object objectForKey:@"data"];
            if (_oneArr.count!=0) {
                [_oneArr removeAllObjects];
            }
            _oneArr = [NSMutableArray arrayWithArray:[noti.object objectForKey:@"data"]];
          // NSLog(@"oneArr===%@",_oneArr);
            
            [_collectView reloadData];
            [self setUpTOP];
        }
    }
    
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    //移除表头通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TDZhuSBiaoTou object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TDZhuSHouse object:nil];

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.title = @"房源管理";
    self.view.backgroundColor = BgColor;
    cellIdDic = [NSMutableDictionary new];
     IDA = [[NSUserDefaults standardUserDefaults] objectForKey:@"STATE"];
    _manager = [TodoHttpManager sharedManager];

   
    _unitArr = [NSArray array];
    _nameDic = [NSDictionary dictionary];
    _busXArr = [[NSMutableArray alloc] init];
    _qiArr = [[NSMutableArray alloc] init];
    _oneArr = [[NSMutableArray alloc] init];
    _firstDic = [[NSMutableDictionary alloc] init];
    _qiIDArr = [NSMutableArray array];
    
    //布局对象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    flowLayout.itemSize = CGSizeMake((B_WIDTH-30)/3,40);
    flowLayout.headerReferenceSize = CGSizeMake(0, 30);//头部
  
    
   
    // 内容 与控件四周的距离
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    _collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight+30+44, B_WIDTH, B_HEIGHT-(LL_StatusBarAndNavigationBarHeight+30+44))collectionViewLayout:flowLayout];
    _collectView.backgroundColor = BgColor;
    _collectView.delegate = self;
    _collectView.dataSource = self;
    [self.view addSubview:_collectView];

    //注册头视图
    [_collectView registerClass:[CustomCollectionViewCell class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];

     [self setupMenuQiArr:_qiArr];
        self.collectView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(BusnessHeaderTageAction)];
 
    
}


-(void)BusnessHeaderTageAction
{
    [self setupMenuQiArr:_qiArr];
    [_collectView.mj_header endRefreshing];
    
}
-(void)setUpTOP
{
    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, B_WIDTH, 30)];
    aView.backgroundColor = [UIColor colorWithHexString:@"#eb6200"];
    [self.view addSubview:aView];
    
    UILabel *oneLab = [[UILabel alloc] init];
    oneLab.text = [NSString stringWithFormat:@"总房源 :%@套",_newZong.length>0?_newZong:@""];
    oneLab.textColor = [UIColor whiteColor];
    oneLab.font = [UIFont systemFontOfSize:12];
    [aView addSubview:oneLab];
    [oneLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(100, 20));
        make.left.equalTo(aView.mas_left).offset(20);
        make.top.equalTo(aView.mas_top).offset(5);
        
    }];
    
    UILabel *twoLab = [[UILabel alloc] init];
    twoLab.text = [NSString stringWithFormat:@"已售 :%@套",_newYi.length>0?_newYi:@""];
    twoLab.textColor = [UIColor whiteColor];
    twoLab.font = [UIFont systemFontOfSize:12];
    [aView addSubview:twoLab];
    [twoLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 20));
        make.left.equalTo(oneLab.mas_right).offset(10);
        make.top.equalTo(aView.mas_top).offset(5);
        
    }];
    
    UILabel *sanLab = [[UILabel alloc] init];
    sanLab.text = [NSString stringWithFormat:@"未售 :%@套",_newWei.length>0?_newWei:@""];
    sanLab.textColor = [UIColor whiteColor];
    sanLab.font = [UIFont systemFontOfSize:12];
    [aView addSubview:sanLab];
    [sanLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(100, 20));
        make.left.equalTo(twoLab.mas_right).offset(10);
        make.top.equalTo(aView.mas_top).offset(5);
        
    }];
}

//-(void)bussniessRrefreshCollection
//{
//      [_manager userZhuShouFangYuanWithType:@"1" withQi:_IDStr withQuYU:nil withLou:bussSeleUnit];
//    [_collectView reloadData];
//}
-(void)setupMenuQiArr:(NSMutableArray *)qiArr
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    RKTagsMenuView *tagMenuView = [[RKTagsMenuView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight+30,self.view.frame.size.width, 44)];
    tagMenuView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:tagMenuView];
    [tagMenuView setTagsArray:qiArr];

    [_manager userZhuShouFangYuanWithType:@"1" withQi:_IDStr withQuYU:nil withLou:bussSeleUnit];
   // [_collectView reloadData];

    //__weak __typeof(self) wself = self;
    [tagMenuView setDidSelectTagBlock:^(NSInteger clickedRow) {

        bussSeleUnit = _qiIDArr[clickedRow];
      //  NSLog(@"------%@",bussSeleUnit);
        if (self.oneArr.count!= 0)
        {
            [self.oneArr removeAllObjects];
        }
//
        //TODO:房源(配套/商业)
        [_manager userZhuShouFangYuanWithType:@"1" withQi:_IDStr withQuYU:nil withLou:bussSeleUnit];
        [cellIdDic removeAllObjects];
        [_collectView reloadData];
        
        
    }];
    
}

#pragma mark - UICollectionViewDelegate&&DateSoucre

//创建头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *oneView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"forIndexPath:indexPath];
  

    NSInteger aa = (B_WIDTH-300)/4;
   
    oneView.backgroundColor = BgColor;
    [self.view addSubview:oneView];
    
    UIButton *redBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    redBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [redBtn setTitleColor:[UIColor blackColor] forState:0];
    [redBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [redBtn setImage:[UIImage imageNamed:@"Color_yishou"] forState:0];
    [redBtn setTitle:@"已售" forState:0];
    [oneView addSubview:redBtn];
    [redBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(55, 20));
        make.left.equalTo(oneView.mas_left).offset(6);
        make.top.equalTo(oneView.mas_top).offset(5);
    }];
    
    UIButton *writeBrn = [UIButton buttonWithType:UIButtonTypeCustom];
    writeBrn.titleLabel.font = [UIFont systemFontOfSize:10];
    [writeBrn setTitleColor:[UIColor blackColor] forState:0];
    [writeBrn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [writeBrn setImage:[UIImage imageNamed:@"Color_bai"] forState:0];
    [writeBrn setTitle:@"未售" forState:0];
    [oneView addSubview:writeBrn];
    [writeBrn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(55, 20));
        make.left.equalTo(redBtn.mas_right).offset(aa);
        make.top.equalTo(oneView.mas_top).offset(5);
    }];
    
    UIButton *blueBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    blueBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [blueBtn setTitleColor:[UIColor blackColor] forState:0];
    [blueBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [blueBtn setImage:[UIImage imageNamed:@"Color_blue"] forState:0];
    [blueBtn setTitle:@"抵押融资" forState:0];
    [oneView addSubview:blueBtn];
    [blueBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 20));
        //make.left.equalTo(oneView.mas_left).offset(6);
        make.top.equalTo(oneView.mas_top).offset(5);
        make.centerX.equalTo(oneView.mas_centerX);
    }];
    
    
    UIButton *greenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    greenBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [greenBtn setTitleColor:[UIColor blackColor] forState:0];
    [greenBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [greenBtn setImage:[UIImage imageNamed:@"Color_lv"] forState:0];
    [greenBtn setTitle:@"内留" forState:0];
    [oneView addSubview:greenBtn];
    [greenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 20));
        make.left.equalTo(blueBtn.mas_right).offset(aa);
        make.top.equalTo(oneView.mas_top).offset(5);
        
    }];
    
    
    UIButton *grayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    grayBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [grayBtn setTitleColor:[UIColor blackColor] forState:0];
    [grayBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [grayBtn setImage:[UIImage imageNamed:@"Color_zi"] forState:0];
    [grayBtn setTitle:@"调房待批" forState:0];
    [oneView addSubview:grayBtn];
    [grayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 20));
        make.right.equalTo(oneView.mas_right).offset(-6);
        make.top.equalTo(oneView.mas_top).offset(5);
        
    }];
    
    
    
    return oneView;
}

// 设置section头视图的参考大小，与tableheaderview类似
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section
{
    
    
    if ([IDA isEqualToString:@"1"])
    {
         return CGSizeMake(0, 0);
    }
    else
    {
        if (section == 0) {
            return CGSizeMake(self.view.frame.size.width,30);
        }
        else {
            return CGSizeMake(0, 0);
        }
 
    }
   
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _oneArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 每次先从字典中根据IndexPath取出唯一标识符，避免复用
    identifier = [cellIdDic objectForKey:[NSString stringWithFormat:@"%ld", indexPath.item]];
    // 如果取出的唯一标示符不存在，则初始化唯一标示符，并将其存入字典中，对应唯一标示符注册Cell
    if (identifier == nil) {
        identifier = [NSString stringWithFormat:@"KeyboardTextCell%@", [NSString stringWithFormat:@"%ld", indexPath.item]];
        [cellIdDic setValue:identifier forKey:[NSString stringWithFormat:@"%ld", indexPath.item]];
        // 注册Cell
        [_collectView registerClass:[CustomCollectionViewCell class]  forCellWithReuseIdentifier:identifier];
        // [_collectView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"CellID"];
    }

    //单元格初始化
    CustomCollectionViewCell *cell = (CustomCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];

    if (_oneArr.count != 0)
    {
        [cell.statusBtn setTitle:[[_oneArr objectAtIndex:indexPath.item] objectForKey:@"room_num"] forState:0];
        cell.statusBtn.tag = indexPath.item;

        NSDictionary *dict = [_oneArr objectAtIndex:indexPath.item];
      //  NSLog(@"==%@",dict[@"is_sale"]);
        [cell setupCollectionViewWithStatus:[NSString stringWithFormat:@"%@",dict[@"is_sale"]] ];
    }

    //找到每一个按钮；
    UIButton*changeButton = cell.statusBtn;
    [changeButton addTarget:self action:@selector(changeButtonClick:)
     forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
    
}

-(void)changeButtonClick:(id)sender
{
 
    //UIView *v = [sender superview];//获取父类view
    CustomCollectionViewCell *cell = (CustomCollectionViewCell *)[sender superview];//获取cell
    NSIndexPath *indexpath = [self.collectView indexPathForCell:cell];//获取cell对应的indexpath;
 
//    NSLog(@"设备图片按钮被点击:%ld%ld",(long)indexpath.section,(long)indexpath.row);
//    BusHouseXVC *busHVC = [[BusHouseXVC alloc] init];
//    busHVC.houseID =[[_oneArr objectAtIndex:indexpath.row]objectForKey:@"uid"];
//    busHVC.statusStr = [[_oneArr objectAtIndex:indexpath.section]objectForKey:@"is_sale"];
//    NSLog(@"这是什么1111111-----------输出的是 %@",busHVC.houseID);
//    
//    [self.navigationController pushViewController:busHVC animated:NO];
    
    _colorStr = [[_oneArr objectAtIndex:indexpath.row]objectForKey:@"is_sale"];
  NSLog(@"-----------=====-----%@",_colorStr);
    if ([_colorStr isEqualToString:@"2"])//已售
    {
        BusRenXViewController *busShouVc = [[BusRenXViewController alloc] init];
        busShouVc.strID1 = [[_oneArr objectAtIndex:indexpath.row]objectForKey:@"uid"];
        NSLog(@"--------------%@",busShouVc.strID1);
        [self.navigationController pushViewController:busShouVc animated:NO];
    }
    else
    {
            BusHouseXVC *busHVC = [[BusHouseXVC alloc] init];
            busHVC.houseID =[[_oneArr objectAtIndex:indexpath.row]objectForKey:@"uid"];
            busHVC.statusStr = [[_oneArr objectAtIndex:indexpath.row]objectForKey:@"is_sale"];
         NSLog(@"--------%@----busHVC.statusStr--%@",busHVC.houseID,busHVC.statusStr);
            [self.navigationController pushViewController:busHVC animated:NO];
    }
    
    
    
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
